<template>
  <transition name="el-zoom-in-top">
    <div
      v-show="visible"
      class="menu el-dropdown__popper el-popper is-light is-pure"
      :style="{ top: y + 10 + 'px', left: x - 10 + 'px' }"
      data-popper-placement="bottom"
    >
      <div class="el-popper__arrow" style="left: 10px"></div>
      <ul class="el-dropdown-menu">
        <li
          class="el-dropdown-menu__item"
          v-for="item in menuItems"
          :key="item.label"
          @click="handleClick(item)"
        >
          {{ item.label }}
        </li>
      </ul>
    </div>
  </transition>
</template>

<script setup lang="ts">
interface MenuProps {
  menuInfo: {
    x: number;
    y: number;
    menuItems: { label: string; onClick: (targetPath: string) => void }[];
    visible: boolean;
    targetPath: string;
  };
}

const props = defineProps<MenuProps>();
const { x, y, menuItems, visible, targetPath } = toRefs(props.menuInfo);

const handleClick = (item: {
  label: string;
  onClick: (arg1: string) => void;
}) => {
  if (item.onClick) {
    item.onClick(targetPath.value);
  }
};

const container = ref<HTMLElement | null>(null);

const emit = defineEmits<{
  (e: "closeMenu"): void;
}>();

/**
 * 页面其他位置点击时隐藏菜单
 *
 * @param event 鼠标事件对象
 */
function handleGlobalClick(event: MouseEvent) {
  if (!container.value?.contains(event.target as Node)) {
    emit("closeMenu");
  }
}

onMounted(() => {
  window.addEventListener("click", handleGlobalClick);
});

onUnmounted(() => {
  window.removeEventListener("click", handleGlobalClick);
});
</script>

<style scoped>
.menu {
  position: fixed;
  z-index: 99999;
}

.menu .el-dropdown-menu__item {
  font-size: 12px !important;
  white-space: nowrap;
}
</style>
